Python 1

Section 3

Native Libraries

In Python we have lots of functions that are available for usage directly. That's what we saw last section when we talked about Built-in functions. However, there are some functions we need, which are not available right away. In this case, we need to import them, like you did in the second section with the math library.


In [ ]:
'''The first thing to do, is to use the 'import' built-in function to
make specific libraries available for usage. The 'import' function can
be used in different aways. Let's see a few of them.'''

# Let's use the math package that you already know
import math                 #simple way to do it
import math as mt           #import library with shorter name
from math import sqrt       #import specific functions from a library
from math import sqrt as sq #import specific functions from a library in abbreviated format
from math import *          #import everything inside a library 

# But what is the difference between them?

In [ ]:
#Sandbox

math


In [ ]:
# So, let's use some functions from math library
import math

#Square Root
n = input('Enter a value: ')
print 'The square root of {} is {}'.format(n,math.sqrt(n))

In [ ]:
# Trigonometry

n = input('Enter a value: ')
print 'The sine of {} is {}'.format(n,math.sin(n))
print 'The cossine of {} is {}'.format(n,math.cos(n))
print 'The tangent of {} is {}'.format(n,math.tan(n))

In [ ]:
# Log
n = input('Enter a value: ')
print 'The natural logarithm of {} is {}'.format(n,math.log(n))
print 'The base-10 logarithm of {} is {}'.format(n,math.log10(n))

In [ ]:
# Constants
print 'The constant pi is equal to {}.'.format(math.pi)
# Euler's number: the unique number whose natural logarithm is equal to one.
print 'The constant e is equal to {}.'.format(math.e)

That are other calculations that can be performed. However, it is necessary to have some data structure. We will see that again in further sections.

os


In [ ]:
# Let's import the library first
import os

In [ ]:
# getcwd and chdir
# this function sets your home directory

path = r"C:\Users\Pereira\Desktop"
print 'Former working environment:',os.getcwd()# get the path ot the current working directory
os.chdir(path)
print 'Current working environment:',os.getcwd()

In [ ]:
# mkdir
# this functions creates a new folder in the working environment
path = r"second_folder"
os.mkdir(path)

In [ ]:
# rename
path = r"C:\Users\Pereira\Desktop\first_folder"
os.rename(path, 'New_name')

In [ ]:
# remove
# deletes the file that was just created
path = r"C:\Users\Pereira\Desktop\New_name"
os.removedirs(path)

In [ ]:
# open
string = 'Python is awesome!!'
file_ = open('test.txt', 'w')
file_.write(string)
file_.close()

In [ ]:
# remove
path = r"C:\Users\Pereira\Desktop\test.txt"
os.remove(path)

In [ ]:
# read
file_ = open('test.txt', 'r')
print file_.read()
file_.close() # very important

In [ ]:
# append
string = '\nIt really is!!'
file_ = open('test.txt', 'a')
file_.write(string)
file_.close()

The os.open function has different modes in order to do different things.

‘r’ – Read mode which is used when the file is only being read

‘w’ – Write mode which is used to edit and write new information to the file (any existing files with the same name will be erased when this mode is activated)

‘a’ – Appending mode, which is used to add new data to the end of the file; that is new information is automatically amended to the end

‘r+’ – Special read and write mode, which is used to handle both actions when working with a file


In [ ]:
# listdir
# provide a list of files in a determined path given
path = r'F:\Joao\Dropbox\Python_I\02_SS_2017\material\exercises'
os.listdir(path)

glob


In [ ]:
from glob import glob
paths = glob(r'F:\Joao\Dropbox\Python_I\02_SS_2017\material\exercises\*1.docx')
# Don't worry if you don't get that. We will talk about it next section.
for path in paths:
    print path

time


In [ ]:
import time
print 'GMT time\n',time.gmtime()
print '\nLocal time\n',time.localtime()

In [ ]:
time.asctime()

In [ ]:
time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())
# https://docs.python.org/2/library/time.html#time.strftime

In [ ]:
time.gmtime()

datetime


In [ ]:
from datetime import datetime
startTime = datetime.now()
len(str(2**10000000))
print datetime.now() - startTime

random


In [ ]:
import random
random.randint(0,100)

Conditions

Conditions are already pretty well known, having the common sysntax 'if' and 'else'. In Python that is not different, but with the addition of another one called 'elif'. Now let's see how to use it in Python. But before we talk about conditions, we have to adress operators and boolean variables. In Python we have operators, which can be represented by:

  • equal (=)
  • comparison (==)
  • bigger than (>)
  • smaller than (<)
  • bigger or equal than (>=)
  • smaller or equal than (<=)
  • different than (!=)

When these operators are used, a boolean (True or False) variable is generated. Let's have a look.


In [ ]:
print 4 > 2
print 2 < 3.7
print 2 > 5
print 2 == 7 # Be careful here
print 5 == 5 # Be careful here

When working with 'if' and 'else' statements, conditions are assessed generating boolean variables as result. Let's see.


In [ ]:
a = 4
b = 'Python'
if a == b: # watch the obligatory element ':'
    print 'Variable a is equal variable b.'
else: # watch the obligatory element ':'
    print 'Variable a is different than variable b.'

In [ ]:
if a != b: # watch the obligatory element ':'
    print 'Variable a is different than variable b.'
else: # watch the obligatory element ':'
    print 'Variable a is equal variable b.'

In [ ]:
b = 'Python'
if 'P' in b: # Try changing the letter 'y'
    print 'Yes, "p" is in {}.'.format(b)
else:
    print 'No, "p" isn\'t in {}.'.format(b) # Have you asked yourself why this '\' is there?

Now, let's take a look how to use the 'elif'. Working with intervals is a good way to understand it.


In [ ]:
# The 'elif' functions allows us to add extra conditions to our if statement.
a = 5
b = 2

if a > b:
    print 'The variable a is bigger than the variable b.'
elif a < b:
    print 'The variable a is smaller than the variable b.'
else:
    print 'The variable a is equal to the variable b.'

In [ ]:
# Let's make the example before a bit better by asking the user for the numbers
a = input('Provide a number: ')
b = input('Provide a second number: ')

if a > b:
    print '{} in bigger than {}.'.format(a,b)
elif a < b:
    print '{} is smaller than {}.'.format(a,b)
else:
    print '{} is equal to {}.'.format(a,b)

In [ ]:
# Task 01: ask the user for a number and use a if statement to see if this number is even or uneven
a = input('Please, enter a number: ')
if a%2==0:
    print 'The number {} is even.'.format(a)
else:
    print 'The number {} is odd.'.format(a)

In [73]:
# Task 02: create a game that asks the user for a number. Then, tell the user if he/she won the game.
a = input('Guess a number between 0 and 20: ')
number = 17
if a==number:
    print 'Great!! You won!!'
else:
    print 'Haha...You lost!! =)'


Guess a number between 0 and 20: 17
Great!! You won!!

In [74]:
# Task 03: create a login/password system where 
# you ask the user for his/her login and password. 
# If either password or login are wrong, print 
# a message with an error.
login = raw_input('Login: ')
passw = raw_input('Password: ')
Login = 'user'
Passw = 'admin'
if login == Login and passw==Passw:
    print 'Access granted!'
elif login != Login and passw==Passw:
    print 'Your login is wrong. Try again!!'
elif login == Login and passw!=Passw:
    print 'Your password is wrong. Try again!!'
else:
    print 'Your login and password are wrong. Try again!!'


Login: 6254287
Password: 7659374
Your login and password are wrong. Try again!!

In [81]:
# Task 04: write a code that asks for the user to write a sentence.
# If the sentence has more then 10 words, print a message that the
# sentence is valid. If the sentence has between 5 and 10, print a
# message that the sentence is short but can be used. If the sentence
# is less then 5, print a message that the setence is too short and
# won't be used. Use the 'string.split()' function to help you with that.
#string = 'Today we are learning about native functions and conditions in Python.'.split()
#string = 'Today we are learning about native functions'.split()
string = 'Today we are learning something'.split()

if len(string)>=10:
    print 'The sentence is valid.'
elif len(string)>5 and len(string)<10:
    print 'The sentence is short, but valid.'
else:
    print 'The sentence is not valid.'


['Today', 'we', 'are', 'learning', 'something']
The sentence is not valid.

In [84]:
# Task 05: create a coin conversion tool. Ask the user to provide a value 
# either in dollars or euros in a specific format (US$ XX,XX or EUR XX,XX)  
# and then convert it to the other option.
# For example: 
#       user's value: US$ XX,XX
#       other option: EUR XX,XX
# Your tool must recognize automatically the type of coin entered and then
# convert the value using the rates:
#       1 dollar = 0,919 EUR
#       1 EUR = 1,088 dollar
# Print the final result in a nice format. For example:
# US$ XX,XX in euros is EUR XX,XX. or EUR XX,XX in dollars is US$ XX,XX.
###########################################################################

m = raw_input('Please provide a value to convert. Please provide the input like US$ 23,12 or EUR 23,12: ')
m_ = float(m[4:].replace(',','.'))

if m[:3]=='US$':
    print 'US$ {} in euros is EUR {}.'.format(m[4:], m_*1.088)
elif m[:3]=='EUR':
    print 'EUR {} in dollars is US$ {}.'.format(m[4:], m_*0.919)
else:
    print 'The value entered is invalid. Please try again.'


Please provide a value to convert. Please provide the input like US$ 23,12 or EUR 23,12: 23,14
The value entered is invalid. Please try again.

Python still have other operators called 'not', 'and' and 'or' (NAO). An easy way to understand is to use boolean variables. Let's try.


In [85]:
# Let's compare True and False using the operators.
print 'True and True is',True and True
print '0 and True is',False and True
print 'False and False is',False and False
print 'True or True is',True or True
print '1 or 0 is',False or True
print '0 or False is',False or False
print 'not True is',not True
print 'not 0 is',not False


True and True is True
0 and True is False
False and False is False
True or True is True
1 or 0 is True
0 or False is False
not True is False
not 0 is True

In [86]:
# You can also combine them.
print 'True and not True is',True and not True
print 'True and False or True is',True and False or True
print 'not True or True and not True and True is', not True or True and not True and True


True and not True is False
True and False or True is True
not True or True and not True and True is False
####### Booleans and Operators####### But how the hell does that work? How is it possible that a string with only Trues ('not True or True and not True and True') turns out as False? Just like math when working with subtraction, addition, multplication and division, with 'not', 'and', 'or' or NAO, there is an specific order to analyse the operators. By now you might have guessed already, but if you didn't, the order is 'not', then 'and' then 'or'. Let see an example: True and not True or False and True or False and not False and not True or False and True or not False and True We have to start with 'not', so let's isolate only 'not' using brackets. True and (not True) or False and True or False and (not False) and (not True) or False and True or (not False) and True True and False or False and True or False and True and False or False and True or True and True Now we go to 'and'. (True and False) or (False and True) or ((False and True) and False) or (False and True) or (True and True) False or False or False or False or True Finally, we analyse the 'or'. False or False or False or False or True = True

In [87]:
True and not True or False and True or False and not False and not True or False and True or not False and True


Out[87]:
True

In [88]:
# Operator can also be used in if statements
string = 'Python'
statement = 'Python is awesome!!'
if string not in statement:
    print 'Something went wrong!!'
else:
    print 'Hell yeah python is awesome \o/'


Hell yeah python is awesome \o/

For the next episode of Python 1...

you will have a journey through:

  • loops (while and for)
  • list comprehentions
  • a loooot of exercises

To be continued...